package com.ybbase.framework.controller.system;

import com.ybbase.framework.base.model.TreeMessage;
import com.ybbase.framework.common.constant.CommonResultCode;
import com.ybbase.framework.common.enums.LogFunType;
import com.ybbase.framework.common.enums.LogType;
import com.ybbase.framework.common.util.BeanUtil;
import com.ybbase.framework.model.po.system.Organization;
import com.ybbase.framework.service.system.LogService;
import io.swagger.annotations.*;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.RestController;
import com.ybbase.framework.base.controller.BaseController;
import com.ybbase.framework.service.system.DictService;
import com.ybbase.framework.model.po.system.Dict;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;

import com.ybbase.framework.base.model.ResponseBean;

import javax.servlet.http.HttpServletRequest;

/**
 * 数字字典表 前端控制器
 *
 * @author cg
 * @since 2019-11-25
 * 云平台2.0
 */
@RestController
@RequestMapping(value = "/dict", produces = {"application/json;charset=UTF-8"})
@Api("数字字典表")
public class DictController extends BaseController {

    private static final Logger LOGGER = LogManager.getLogger(DictController.class);

    @Autowired
    private DictService targetService;
    @Autowired
    private LogService logService;


    /**
     * 数字字典表分页查询
     *
     * @param pageIndex 页数
     * @param step      每页数量
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/list")
    @ApiOperation(value = "数字字典表分页查询", notes = "数字字典表分页查询", response = ResponseBean.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "rows", value = "每页行数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "dict", value = "数字字典表", dataType = "Dict对象")
    })
    public ResponseBean findListByPage(@RequestParam(name = "current", defaultValue = "1") int pageIndex,
                                       @RequestParam(name = "size", defaultValue = "20") int step, Dict dict) {
        try {

            Page<Dict> page = new Page(pageIndex, step);
            if (dict.getTypeinfo() != null) {
                QueryWrapper<Dict> queryWrapper = new QueryWrapper<Dict>();
                queryWrapper.lambda().eq(Dict::getTypeinfo, dict.getTypeinfo());
                targetService.page(page, queryWrapper);
            } else {
                Wrapper<Dict> wrapper = new QueryWrapper<Dict>();
                targetService.page(page, wrapper);
            }
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "数字字典表分页查询" + CommonResultCode.SUCCESS.getMsg(), page);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("数字字典表分页查询异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "数字字典表分页查询" + CommonResultCode.FAIL.getMsg());
        }
    }


    /**
     * 数字字典表获取全部数据
     *
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/all")
    @ApiOperation(value = "数字字典表获取全部数据", notes = "数字字典表获取全部数据")
    public ResponseBean findAll() {
        TreeMessage treeMessage = new TreeMessage();
        try {
            List<Dict> models = targetService.list();
            treeMessage.setCode("200");
            treeMessage.setMessage("数字字典表获取全部数据" + CommonResultCode.SUCCESS.getMsg());
            return new ResponseBean(treeMessage, targetService.findSortDict(models));
            //targetService.findSortDict(models)
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("数字字典表获取全部数据：{}", e.getMessage());
            treeMessage.setCode("400");
            treeMessage.setMessage("数字字典表获取全部数据" + CommonResultCode.SUCCESS.getMsg());
            return new ResponseBean(treeMessage, new ArrayList<>());
        }
    }

    /**
     * 数字字典表根据ID查找数据
     *
     * @param id 唯一编码
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @GetMapping("/find")
    @ApiOperation(value = "数字字典表根据ID查找数据", notes = "数字字典表根据ID查找数据")
    @ApiImplicitParam(required = true, name = "id", value = "唯一编码", dataType = "Long")
    public ResponseBean find(@RequestParam("id") Long id) {
        try {
            Dict dict = targetService.getById(id);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "数字字典表根据ID查找数据" + CommonResultCode.SUCCESS.getMsg(), dict);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("数字字典表根据ID查找数据异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "数字字典表根据ID查找数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 数字字典表保存数据
     *
     * @param dict 数字字典表
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @PostMapping("/save")
    @ApiOperation(value = "数字字典表保存数据", notes = "数字字典表保存数据")
    @ApiImplicitParam(required = true, name = "dict", value = "数字字典表", dataType = "Dict对象")
    public ResponseBean save(HttpServletRequest request) {
        try {
            BeanUtil beanUtil = new BeanUtil();
            Dict dict = (Dict) beanUtil.mapToObject(request.getParameterMap(), Dict.class);
            targetService.saveDict(dict);
            logService.saveLog(LogType.add.getEnumKey(), LogFunType.dict.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "数字字典表保存数据" + CommonResultCode.SUCCESS.getMsg(), dict);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("数字字典表保存数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "数字字典表保存数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 数字字典表更新数据
     *
     * @param dict 数字字典表
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @PutMapping("/update")
    @ApiOperation(value = "数字字典表更新数据", notes = "数字字典表更新数据")
    @ApiImplicitParam(required = true, name = "dict", value = "数字字典表", dataType = "Dict对象")
    public ResponseBean update(@RequestBody Dict dict) {
        try {
            targetService.updateById(dict);
            logService.saveLog(LogType.edit.getEnumKey(), LogFunType.dict.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "数字字典表更新数据" + CommonResultCode.SUCCESS.getMsg(), dict);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("数字字典表更新数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "数字字典表更新数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 数字字典表删除数据
     *
     * @param ids 批量删除数据
     * @return ResponseBean
     * @author cg
     * @date 2019-11-25
     * @since cloud2.0
     */
    @DeleteMapping("/del")
    @ApiOperation(value = "数字字典表删除数据", notes = "数字字典表删除数据")
    @ApiImplicitParam(required = true, name = "ids", value = "批量删除数据", dataType = "List<Long>")
    public ResponseBean del(@RequestParam("ids") List<Long> ids) {
        try {
            targetService.removeByIds(ids);
            logService.saveLog(LogType.del.getEnumKey(), LogFunType.dict.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "数字字典表删除数据" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("数字字典表删除数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "数字字典表删除数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 根据id删除
     *
     * @param id 数据id
     * @return ResponseBean
     * @author phm
     * @date 2020-01-08 00:07:05
     * @since cloud2.0
     */
    @GetMapping("/delete")
    @ApiOperation(value = "数字字典表删除数据", notes = "数字字典表删除数据")
    @ApiImplicitParam(required = true, name = "id", value = "根据id删除", dataType = "Integer")
    public ResponseBean delete(Integer id) {
        try {
            targetService.removeById(id);
            logService.saveLog(LogType.del.getEnumKey(), LogFunType.dict.getEnumKey());
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "数字字典表删除数据" + CommonResultCode.SUCCESS.getMsg());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("数字字典表删除数据：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "数字字典表删除数据" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 根据类型查询数据字典
     *
     * @param type
     * @return
     * @author cg
     * @date 2019-12-21 22:57
     * @since cloud2.0
     */
    @GetMapping("/getDictByType")
    @ApiOperation(value = "根据类型查询数据字典", notes = "根据类型查询数据字典")
    @ApiImplicitParam(required = true, name = "type", value = "类型", dataType = "String")
    public ResponseBean getDictByType(@RequestParam String type) {
        try {
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Dict::getType, type);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "数字字典表删除数据" + CommonResultCode.SUCCESS.getMsg(),
                    targetService.list(queryWrapper));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("根据类型查询数据字典：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "根据类型查询数据字典" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 获取数据字典树
     *
     * @return
     * @author phm
     * @date 2020-01-08 00:06:42
     */
    @GetMapping("/getTree")
    @ApiOperation(value = "数据字典树", notes = "数据字典树")
    public ResponseBean getTree() {
        try {
//            List<Dict> list = targetService.list();
//            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "数据字典树" + CommonResultCode.SUCCESS.getMsg(),targetService.findSortDict(list));
            List<Dict> listTree = targetService.getTree();
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "数据字典树" + CommonResultCode.SUCCESS.getMsg(), listTree);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("数据字典树获取异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "数据字典树" + CommonResultCode.FAIL.getMsg());
        }
    }

    /**
     * 数字字典表根据parentId查找分页数据
     *
     * @param id 唯一编码
     * @return ResponseBean
     * @author phm
     * @date 2020-01-08 00:06:24
     * @since cloud2.0
     */
    @GetMapping("/findByParentId")
    @ApiOperation(value = "数字字典表根据parentId查找分页数据", notes = "数字字典表根据parentId查找分页数据", response = ResponseBean.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "rows", value = "每页行数", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "dict", value = "数字字典表", dataType = "Dict对象")
    })
    public ResponseBean findByParentId(@RequestParam(name = "current", defaultValue = "1") int pageIndex,
                                       @RequestParam(name = "size", defaultValue = "20") int step, Integer parentId) {
        try {
            QueryWrapper<Dict> queryWrapper = new QueryWrapper<Dict>();
            Page<Dict> page = new Page<>(pageIndex, step);
            targetService.findByParentId(page, queryWrapper, parentId);
            return new ResponseBean(CommonResultCode.SUCCESS.getCode(), "数字字典表根据parentId查找数据" + CommonResultCode.SUCCESS.getMsg(), page);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("数字字典表根据parentId查找数据异常：{}", e.getMessage());
            return new ResponseBean(CommonResultCode.FAIL.getCode(), "数字字典表根据parentId查找数据" + CommonResultCode.FAIL.getMsg());
        }
    }

}
